#include <stdio.h> 
#include <stdlib.h>
#include <unistd.h>
#include <string.h>


char *default_path = "./dest.bin";

int            src_len  = 0;
unsigned int   src_file_ver  = 0;
unsigned short src_check_sum = 0x5555;


int ret = 0;
unsigned char buff[1024] = {0};


void print_opt_info(void)
{

        printf("please check your input:                                    \n");
        printf("    [-i]   input_file.bin,which file you will check         \n");
}


int main(int argc, char *argv[])
{
	int ch;

        if(argc < 2){
                print_opt_info();
                return EXIT_FAILURE;
        }
       
       /*
	* -i 源文件
	*/	
	while((ch = getopt(argc, argv, "i:")) != -1)
        {
                switch(ch)
                {
                        case 'i':
                                default_path     = optarg;
                                break;
                        default:
                                break;
                }
        }

        if(default_path == NULL){
                print_opt_info();
                return EXIT_FAILURE;
        }
	/* 
	 * 打开源文件
	 */
	FILE *src_fp = fopen(default_path, "rb");
       	if (!src_fp) {
		perror("fopen src_fp");
		return EXIT_FAILURE;
	}
        /*
         * 将源文件的文件指针偏移到文件尾，获取文件长度
         */
        fseek(src_fp, 0, SEEK_END);
        src_len = ftell(src_fp)-256;
	/*
	 * 将源文件的文件指针偏移到文件头
	 */
	fseek(src_fp, 0, SEEK_SET);
	unsigned short tmp_check_sum = 0x5555;
	/*
	 * 读取文件头 
	 */
        if((ret = fread(buff, sizeof(*buff), 256, src_fp)) == 256)
	{
		for(int i = 0; i < 254; i++){
			tmp_check_sum += buff[i];
		}
		if (tmp_check_sum == (buff[254] + (buff[255] << 8))){
			printf("file head check successed!\n");
		}else{
			printf("file head check failed!\n");
			return EXIT_FAILURE;
		}

		if (src_len == (buff[0] + (buff[1] << 8) + (buff[2] << 16) + (buff[3] << 24))){
			printf("file len check successed!\n");	
		}else{
			printf("file len check failed!\n");
			return EXIT_FAILURE;
		}
                src_check_sum = buff[130] + (buff[131] << 8);
	}else{
		return EXIT_FAILURE;
	}

	/*
	 * 将目标文件的文件指针偏移到第256字节
	 */
	fseek(src_fp, 256, SEEK_SET);
        /*
         * 循环读取源文件计算校验同时将源文件拷贝到目标文件中
         */
	tmp_check_sum = 0x5555;
        int read_count = 0;
        while((ret = fread(buff, sizeof(*buff), sizeof(buff)/sizeof(*buff), src_fp)) > 0)
        {
                for(int i = 0; i < ret; i++){
                        tmp_check_sum += buff[i];
                }
                read_count += ret;
        }
	if ((read_count == src_len) && (tmp_check_sum == src_check_sum)){
		printf("file check sum successed!\n");	
	}else{
		printf("file check sum failed!\n");
		return EXIT_FAILURE;
	}

	fclose(src_fp);

	return EXIT_SUCCESS;
} 
